//index.js
//获取应用实例
const App = getApp();

Page({
  data: {
    current_page: 1,
    last_page: 1,
    articleList:[],
    categoryList:[],
    category_id:0,
    categoryIndex: 0, //当前选中标题的下标
    scrollLeft: 0, //tab滚动条的位置
  },

  onLoad: function () {
    
  },

  /**
   * 跳转文章详情页
   */
  onTargetDetail(e) {
    wx.navigateTo({
      url: '/pages/article/detail/index?article_id=' + e.currentTarget.dataset.article_id
    });
  },

  getCategory(){
    let _this = this;
    App._get('article/index', {
    }, function (result) {
      _this.setData({
        categoryList:result.data.categoryList,
        category_id:result.data.categoryList[0].category_id
      })
      _this.getList()
    });
  },

  getList(){
    let app = this
    let articleList = app.data.articleList
    let current_page = app.data.current_page
    if (current_page > app.data.last_page) {
      return false
    }
    App._get('article/lists', {
      category_id:app.data.category_id,
      page:current_page
    }, function (res) {
      let array = res.data.list.data
      array.forEach(element => {
        articleList.push(element)
      })
      app.setData({
        articleList: articleList,
        current_page: current_page,
        last_page: res.data.list.last_page
      })
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      current_page:1,
      last_page:1,
      categoryIndex:0,
      articleList:[]
    })
    this.getCategory()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    // 页面上拉触底事件的处理函数
    let app = this
    // 获取当前页面的页数并赋值给当前新的参数
    let current_page = app.data.current_page
    current_page++
    app.setData({
      current_page
    })
    app.getList()
  },

  //点击切换标题
  changeTitle(event) {
    let index = event.target.dataset.current; //当前点击标题的index
    let category_id = event.target.dataset.category_id; //当前点击标题的index
    this.setData({
      categoryIndex: index,
      category_id: category_id,
      current_page:1,
      last_page:1,
      articleList:[]
    })
    this.getList()
  },

  //滑动切换内容
  changeContent(event) {
    let current = event.detail.current;
    console.log(current)
    let singleNavWidth = wx.getSystemInfoSync().windowWidth / 5;
    this.setData({
      currentIndex: current,
      scrollLeft: (current - 2) * singleNavWidth
    });
  }
})